package com.itheima.d3_tcp.no2;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 目标：TCP多发多收（服务端）（使用线程池优化）
 */
public class ServerDemo02C {
    public static void main(String[] args) throws IOException {
        System.out.println("--------------服务端启动了（使用线程池优化）---------------");

        //创建线程池对象
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5,
                2, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(8),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        //1.创建ServerSocket对象，注册服务端端口号
        ServerSocket ss = new ServerSocket(8888);

        while (true) {
            //2.获取客户端的连接，只要由客户端连上就能返回socket
            Socket socket = ss.accept();

            //3.获取字节输入流对象，通过字节输入流获取客户端发送过来的数据
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //获取ip地址
                        String ip = socket.getInetAddress().getHostAddress();
                        //3 获取字节输入流对象，通过字节输入流获取客户端发送过来的数据
                        InputStream is = socket.getInputStream();
                        IOUtils.copy(is, System.out);
                        //e.printStackTrace();
                        System.out.println(ip + "下线了，走好不送~");
                        //4 释放资源
                        is.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
